<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="file" name="" id="">
  <script>
    const drawFrame = (vdo) => {
      return new Promise(resolve => {
        // 创建 canvas
        const canvas = document.createElement('canvas')
        // 获取 canvas 的上下文
        const ctx = canvas.getContext('2d')
        // 获取视频的宽度和高度
        const width = vdo.videoWidth
        const height = vdo.videoHeight
        canvas.width = width
        canvas.height = height
        // 将视频绘制到canvas 上
        ctx.drawImage(vdo, 0, 0, width, height)
        // 如果这个图片需要上传，就需要转换成 blob 二进制数据。或者预览就需要这个图片的地址
        canvas.toBlob((blob) => {
          resolve({
            blob: blob,
            url: URL.createObjectURL(blob)
          })
        })
      })
    }

    const captureFrame = (vdoFile, time = 0) => {
      return new Promise(r => {
        const vdo = document.createElement('video')
        // 将 video 文件转换成地址
        const url = URL.createObjectURL(vdoFile)
        // url blob:http://127.0.0.1:5501/0791b70a-a4c9-408b-923d-b595c7b91ed3
        vdo.src = url
        vdo.currentTime = time // 将视频定格在某个时间点
        vdo.autoplay = true
        vdo.muted = true // 由于浏览器限制不允许自动播放，设置静音之后就可以自动播放了
        vdo.oncanplay = async () => {
          const imgInfo = await drawFrame(vdo)
          r(imgInfo)
        }
      })
    }

    const createPreview = (iframe) => {
      const imgEl = document.createElement('img')
      imgEl.src = iframe.url
      imgEl.width = 400
      imgEl.height = 300
      imgEl.style.display = 'block'
      document.body.appendChild(imgEl)
    }

    const inpEl = document.querySelector('input[type="file"]')
    inpEl.addEventListener('change', async(e) => {
      const file = e.target.files[0]
      for (let i = 0; i < 10; i++) {
        const imgInfo = await captureFrame(file, i * 1)
        createPreview(imgInfo)
      }
    })
  </script>
</body>
</html>
